package com.ak47.cms.cms.kong

import com.ak47.cms.cms.dao.KongShopRepository
import org.openqa.selenium.Dimension
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions
import org.openqa.selenium.remote.CapabilityType
import org.openqa.selenium.remote.DesiredCapabilities
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.*


/**
 * @author: Jack
 * 2020/11/8 21:37
 */


@Service
class ChromeDriverUtil {

    val log = LoggerFactory.getLogger(this::class.java)

    val myShopUrl = "http://shop.kongfz.com/431409/"
    fun followApi(shopId: String) = "http://shop.kongfz.com/widget/ajax?widget=shopInfo&tpl=store&api=collect&shopId=${shopId}&_=1604766090357"

    val headless = false
    val driver = ChromeDriver(chromeOptions(headless))

    @Autowired
    lateinit var kongShopRepository: KongShopRepository


    /**
     * 启动chrome浏览器,手动登陆我的店铺,然后读取数据库里面的shopId,批量进行关注收藏.
     */
    fun followShop(): String {
        driver.manage().window().size = Dimension(1400, 1600)
        try {
            driver.get(myShopUrl)

            // 手动登陆我的店铺
            Thread.sleep(1000 * 60 * 1)

            var count = 0
            kongShopRepository.findAll().forEach {
                val shopId = it.shopId
                driver.get(followApi(shopId))
                Thread.sleep(Random().nextInt(51).toLong())
                println(count++)
            }

        } catch (e: Exception) {
            log.info("followShop:", e)
        }
        return "启动 ChromeDriver"
    }

    /**
     * 禁止chrome弹出忽略网站证书错误提示 headless
     * https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver
     * webdriver.chrome.driver
     *
     * @return
     */
    fun chromeOptions(headless: Boolean): ChromeOptions? {
//    System.setProperty("webdriver.chrome.driver", "chromedriver") //指定驱动路径
        System.setProperty("webdriver.chrome.driver", "/Users/jack/code/cms-spider/chromedriver") //指定驱动路径
        val options = ChromeOptions()
        val capabilities = DesiredCapabilities.chrome()

        // SSL Certificate
        capabilities.setCapability(CapabilityType.TAKES_SCREENSHOT, true)
        capabilities.setCapability(CapabilityType.SUPPORTS_JAVASCRIPT, true)

        // options.addArguments("--headless");
        options.addArguments("--start-maximized")
        options.addArguments("--ignore-certificate-errors")
        if (headless) {
            options.addArguments("headless")
        }
        return options
    }

}


